define(['./../initial', './../service/chartsFactory', './../model/locationPoints', './../model/project'], function() {
    var app = angular.module('App.home');
    app.controller('summaryCtrl', ['$scope', '$location', '$rootScope', 'chartsFactory', 'LocationPoints', 'Project', '$window',
        function($scope, $location, $rootScope, chartsFactory, LocationPoints, Project, $window) {

            $scope.summaryResults = [];
            $scope.showScrollTop = false;
            angular.element($window).bind('resize', function() {
                $scope.$apply(function() {
                    $rootScope.smallScreen = document.documentElement.clientWidth < 1025 ? true : false;
                });
            });

            var summaryParams = $scope.summaryParams = JSON.parse(window.localStorage.getItem('summaryParams'));
            $rootScope.smallScreen = document.documentElement.clientWidth < 1025 ? true : false;
            $rootScope.curPrj = $.extend(new Project(), {
                name: summaryParams.name,
                prjId: summaryParams.prjId
            });

            var dates = [summaryParams.startDate, summaryParams.endDate];
            $scope.summaryResults = summaryParams.monitorItems;
            $scope.summaryResults[0].active = true;

            $scope.singlePointQuery = function(ptName) {
                chartsFactory.openSinglePointModal(ptName);
            };

            $scope.goBack = function() {
                $window.open('/');
            };

            // .getRecentFuzzyChanges = function(prjId, monitorType, clickDates, location, fuzzy) {
            $scope.summaryResults.forEach(function(item, index) {
                LocationPoints.prototype.getRecentFuzzyChanges.call(item, summaryParams.prjId, item.monitorType, dates, item.location, 1)
                    .then((function(index) {
                        return function(data) {
                            var chartId = '#summaryChart' + index;
                            chartsFactory.createPointsChartByLocationSummary(chartId, data);
                            //将数据赋值
                            $scope.summaryResults[index].recentChanges = data;
                        };
                    })(index));
            });
            var __page = $('#summaryPage');


            var activeIndex = 0;
            $scope.scrollTo = function(index, $event) {
                var chartId = '#summaryHeader' + index;
                var topOld = __page.scrollTop();
                var top = $(chartId).offset().top;

                __page.animate({
                    scrollTop: index === 0 ? 0 : top + topOld
                }, {
                    duration: 'slow'
                });
            };

            function setActiveItem(index) {
                $scope.summaryResults.forEach(function(item) {
                    item.active = false;
                });


                if ($scope.$root.$$phase != '$apply' && $scope.$root.$$phase != '$digest') {
                    $scope.$apply(function() {
                        $scope.summaryResults[index].active = true;
                    });
                }

            }

            $scope.scrollToTop = function() {
                $scope.scrollTo(0);
            };

            function checkTop(top) {
                if (top > 200) {
                    if ($scope.showScrollTop === false) {
                        $scope.$apply(function() {
                            $scope.showScrollTop = true;
                        });
                    }
                } else {
                    if ($scope.showScrollTop === true) {
                        $scope.$apply(function() {
                            $scope.showScrollTop = false;
                        });
                    }
                }
            }
            
            __page.on('scroll', function() {
                var top = __page.scrollTop();
                checkTop(top);
                var bottom = top + $(window).height();
                var height = document.getElementById('summaryPage').scrollHeight;
                if (bottom === height) {
                    activeIndex = $scope.summaryResults.length - 1;
                    setActiveItem(activeIndex);
                    return;
                }
                var index = -1;

                for (var i = 0; i < $scope.summaryResults.length; i++) {
                    var chartId = '#summaryHeader' + i;

                    var divTop = $(chartId).offset().top;
                    var divHeight = $(chartId).height();
                    if (divTop > -divHeight + 200 && divTop < 200) {
                        index = i;
                        break;
                    }
                }

                if (index === -1) return;
                if (index != activeIndex) {
                    activeIndex = index;
                    setActiveItem(index);
                }

            });

            $scope.export = function() {
                var svgs = $('svg');
                var doc = new jsPDF('p', null, 'a3'); // A4 portrait
                svgs.each(function(index, element) {
                    var canvas = document.createElement('canvas');
                    var width = this.clientWidth;
                    var height = this.clientHeight;
                    var scale = 2;
                    canvas.setAttribute('width', width * scale);
                    canvas.setAttribute('height', height * scale);
                    if (canvas.getContext && canvas.getContext('2d')) {
                        var context = canvas.getContext('2d');
                        // draw chart
                        var svgString = new XMLSerializer().serializeToString(this);
                        context.drawSvg(svgString, 0, 30, width * scale, height * scale);
                        // draw background
                        context.fillStyle = '#FFFFFF';
                        context.fillRect(0, 0, width * scale, 30);
                        // draw title
                        context.font = (2 * scale) + 'em "Microsoft Yahei"';
                        var title = $scope.summaryResults[index].location + "-" + $scope.summaryResults[index].monitorType;
                        var titleWidth = context.measureText(title).width;
                        context.fillStyle = '#000000';
                        context.fillText(title, (width * scale - titleWidth) / 2, 40);
                        var data = canvas.toDataURL('image/jpeg');
                        // output to pdf
                        if (index && index % 3 === 0) { // a page contains 3 charts at most
                            doc.addPage();
                        }
                        doc.addImage(data, 'JPEG', 0, (117 + 30) * (index % 3) + 5, 297, 117, undefined, 'none');
                    } else {
                        alert('error');
                    }
                    //$('#summaryContainer').append(canvas);
                });
                doc.save($scope.summaryParams.name + '总评报表.pdf');
            };

        }
    ]);
});
